package com.qh.org.service.impl;

import com.qh.basic.service.impl.BaseServiceImpl;
import com.qh.org.domain.Department;
import com.qh.org.mapper.DepartmentMapper;
import com.qh.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
/**
 * 业务实现类：部门
 */
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        //1.先查询出所有的部门,存到map中[内存中]，后面要用，就不用查询数据库了
        List<Department> departments = departmentMapper.loadAll();
        Map<Long, Department> map = new HashMap<>();
        for (Department department:departments) {
            map.put(department.getId(),department);
        }
        //2.遍历所有部门如果没有parent_id直接装到树里面
        ArrayList<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if (department.getParent_id() == null){//没有上级部门
                deptTree.add(department);
            }else {//有上级部门的
                //1.先查到parent_id
                Long parent_id = department.getParent_id();
                //2.通过parent_id找到自己的父部门
                Department departmentParent = map.get(parent_id);
                //3.将自己装到  父部门 的children中
                departmentParent.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
